#ifndef HF_H_
#define HF_H_

#include <iostream>

#include "qtapi.h"
#include "sys/time.h"

class COrderTimeRecording : public IPolicy {
 private:
  IFutureTrader* m_pClient;
  OrderField* m_pOpenOrder;
  OrderField* m_pCloseOrder;
  MarketDataField* tempMD;
  char m_sInstrumentID[32];
  int m_nTicks;
  struct timeval tv;
  int m_nMaxOrderNumber;
  int m_nOrderNumber;
  int m_nAskVol;
  int m_nBidVol;
  int m_nTickSize;
  int m_nCloseTd;
  // struct timeval tv2;
  // struct timeval tv3;

 public:
  COrderTimeRecording();
  virtual ~COrderTimeRecording();

  // called by the framework when a policy thread is started.
  // after this call,the method will accept new market data;
  virtual void OnStarted() {
    SubscribeMarketData(m_sInstrumentID);

    FutureInstrumentField field = {};

    strcpy(field.InstrumentID, "zn2304");
    m_pClient->GetInstrument(&field);
    printf("field ExpireDate %s  tick %f  \n", field.ExpireDate,
           field.PriceTick);
    string inst;
    int total = 0, closable = 0, today = 0;
    m_pClient->Sell("zn2304", 1, 100, 1);
    sleep(3);
    m_pClient->GetLongPos("zn2304", total, closable, today);
    // m_pClient->Buy("zn2304", 2, 300);
    printf("total  %d  closable  %d  today %d  \n", total, closable, today);
  }

  // framework will call this method according settings in
  // policyserver.xml
  virtual void OnSetFutureTrader(const char* Alias, IFutureTrader* pTrader) {
    m_pClient = pTrader;
  }

  // policy can overwrite this method to accept future marketdata,
  // and submit order in this function;
  virtual void OnNewFutureMD(MarketDataField* pMD) { m_nTicks++; }

  virtual void OnFOrderChanged(OrderField* pOrder, int nLastTradedVolume,
                               int nFilledVolume, char cOrderStatus) {}
  // 定时器触发事件
  // over write parent virtual
  virtual void OnTimer(OrderField* pField, long nAction) {
    if (nAction == 1 && pField != NULL) {
      if (pField->OrderStatus != '5' && pField->OrderStatus != '1' &&
          pField->OrderSysID[0] != '\0') {
        // pField->
        m_pClient->CancelOrder(pField);

        // m_pClient->RegisterTimer(300, 1, pField);
      }
    }
  }
  virtual void OnSetParam(const char* pszName, const char* pszValue) {
    if (strcmp(pszName, "sInst") == 0) {
      strcpy(m_sInstrumentID, pszValue);
    } else if (strcmp(pszName, "nMaxNum") == 0) {
      m_nMaxOrderNumber = atoi(pszValue);
    } else if (strcmp(pszName, "nAskVol") == 0) {
      m_nAskVol = atoi(pszValue);
    } else if (strcmp(pszName, "nBidVol") == 0) {
      m_nBidVol = atoi(pszValue);
    } else if (strcmp(pszName, "nTickSize") == 0) {
      m_nTickSize = atoi(pszValue);
    } else if (strcmp(pszName, "nCloseTd") == 0) {
      m_nCloseTd = atoi(pszValue);
    }

    printf("OnSetParam \n");
  }
  virtual void Release() {}
};

extern "C" {
IPolicy* CreatePolicy(void) { return new COrderTimeRecording(); }
}

#endif /* HF_H_ */
